package com.clas.liu.myapplication.view.fragment.impl;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.info.Info;
import com.clas.liu.myapplication.model.entity.info.InfoData;
import com.clas.liu.myapplication.presenter.impl.BaseFragmentPresenter;
import com.clas.liu.myapplication.view.activity.impl.SearchActivity;
import com.clas.liu.myapplication.view.adapter.NormalInfoAdapter;
import com.clas.liu.myapplication.view.util.NetworkHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liu on 2019/5/11.
 */

public class SearchInfoFragment extends BaseFragment {

    private View root;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    private NormalInfoAdapter adapter;
    private LinearLayoutManager layoutManager;
    private SearchActivity activity;
    private Handler handler;

    private int page_no = 1;
    private final int page_size = 10;
    private List<Info> infos;
    private boolean isRefresh = true;
    private boolean isAll = false;
    private int lastVisibleItem;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_search_info_layout, container, false);
        findView();
        init();
        setListener();
        return root;
    }

    private void init() {
        refreshLayout.setRefreshing(true);
        activity = (SearchActivity) getActivity();
        handler = new Handler();
    }
    public Handler getHandler() {
        return handler;
    }
    public void setHandler(Handler handler) {
        this.handler = handler;
    }
    private void setListener() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                infoRefresh();
            }
        });
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (adapter != null && newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount()) {
                    if (!isAll)
                        activity.searchInfo(activity.getsearchKey(),page_no,page_size);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void findView() {
        recyclerView = root.findViewById(R.id.fragment_search_info_rv);
        refreshLayout = root.findViewById(R.id.fragment_search_info_refresh);
    }

    public void infoRefresh() {
        if (NetworkHelper.isNetworkAvailable(activity)) {
            page_no = 1;
            isRefresh = true;
            activity.searchInfo(activity.getsearchKey(),page_no,page_size);
        } else {
            refreshLayout.setRefreshing(false);
            showToast("亲亲，网好像断了呢!~");
        }
    }

    public void FailBecauseNetReturn(final int code) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
            }
        });
    }

    public void InfoReturn(int code, final InfoData data) {
        if (infos == null) {
            infos = new ArrayList<>();
        }
        if (isRefresh) {
            infos.clear();
            isRefresh = false;
        }
        infos.addAll(data.getData());
        handler.post(new Runnable() {
            @Override
            public void run() {

                if (isRefresh) {
                    if (adapter != null)
                        adapter.deleteLoadingMore(false);
                }
                recyclerView.setVisibility(View.VISIBLE);
                refreshLayout.setRefreshing(false);
                if (layoutManager == null) {
                    layoutManager = new LinearLayoutManager(activity);
                    recyclerView.setLayoutManager(layoutManager);
                }
                if (adapter == null) {
                    adapter = new NormalInfoAdapter(activity, infos);
                    recyclerView.setAdapter(adapter);
                } else
                    adapter.update(infos);
                if (data.getPageNum() == data.getPages()) {
                    adapter.deleteLoadingMore(true);
                    isAll = true;
                } else if (data.getPageNum() < data.getPages()) {
                    page_no++;
                    isAll = false;
                }
            }
        });
    }

    public void setIsRefresh(Boolean is) {
        this.isRefresh = is;
    }

    @Override
    protected BaseFragmentPresenter getPresenter() {
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        handler = null;
    }
}
